package college.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import college.constants.Constants;
import college.dao.Attendance;
import college.dao.AttendanceId;
import college.dao.Branch;
import college.dao.ContactDetails;
import college.dao.Student;
import college.exception.SaveException;
import college.model.AttendanceFormModel;
import college.service.CollegeService;
import college.util.ExcelFileGenerator;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	@Autowired
	CollegeService collegeService;

	@RequestMapping(value = "/branchform")
	public String branchForm(@ModelAttribute("branch") Branch branch) {
		System.out.println("HomeController: Passing through branchform...");
		return "branchform";
	}
	
	@RequestMapping(value = "/generateexcel")
	public String generateExcel(HttpServletRequest request,Model model) {
		List<Attendance> attendanceList = (List<Attendance>)request.getSession().getAttribute("attendanceList");
		System.out.println("HomeController: Passing through generateexcel...");
		//ExcelFileGenerator.createExcelFile("attendace.xls", headings, attendanceList)generate 
		model.addAttribute("attendanceList", attendanceList);
		return "attendancereport";
	}
	@RequestMapping(value = "/home")
	public String home() {
		System.out.println("HomeController: Passing through home......");
		return "home";
	}

	@RequestMapping(value = "/savebranch")
	public String saveBranch(@ModelAttribute("branch") Branch branch,
			Model model) {
		System.out.println("HomeController: Passing through savebranch...");
		try {
			collegeService.saveBranch(branch);
		
			model.addAttribute("successMessage", Constants.SAVED_SUCCESSFULLY);
		} catch (SaveException exception) {
			model.addAttribute("errorMessage", exception.getErrorMessage());
		}

		return "branchform";
	}

	@RequestMapping(value = "/studentform")
	public String studentForm(@ModelAttribute("student") Student student,
			Model model) {
		System.out.println("HomeController: Passing through studentform...");
		model.addAttribute("branchList", collegeService.findAllBranches());

		return "studentform";
	}

	@RequestMapping(value = "/savestudent")
	public String saveStudent(@ModelAttribute("student") Student student,
			BindingResult bindingResult, Model model) {
		System.out.println("HomeController: Passing through savestudent...");
		try {
			student.getContactDetails().setCid(student.getHtno().toUpperCase());
			student.getContactDetailses().add(student.getContactDetails());
			collegeService.saveStudent(student);
			model.addAttribute("successMessage", Constants.SAVED_SUCCESSFULLY);
		} catch (SaveException exception) {
			model.addAttribute("errorMessage", exception.getErrorMessage());
		}
		// ModelAndView mv = new ModelAndView("studentform", "command",
		// student);
		// mv.addObject("branchList", collegeService.findAllBranches());
		model.addAttribute("branchList", collegeService.findAllBranches());
		return "studentform";
	}

	@RequestMapping(value = "/attendanceform")
	public String attendanceForm(
			@RequestParam("branch") String branchCode, @RequestParam("year") String year, @RequestParam("sem") String sem,  @ModelAttribute("attendanceFormModel") AttendanceFormModel attendanceFormModel,
			Model model) {
		System.out.println("HomeController: Passing through attendanceform...");
		// List<Attendance> attendenceList = new ArrayList<Attendance>();
		model.addAttribute("studentList", collegeService.findAllstudents(branchCode, year, sem));
		// model.addAttribute("attendenceList", attendenceList);
		// model.addAttribute("attendance", new Attendance());
		return "attendanceform";
	}

	@RequestMapping(value = "/saveattendance")
	public String saveAttendance(
			@ModelAttribute("attendanceFormModel") AttendanceFormModel attendanceFormModel,
			Model model) {
		System.out
				.println("HomeController: Passing through savesattendance...");
		
		List<Attendance> alist = new ArrayList<Attendance>();
		for (Attendance attendance : attendanceFormModel.getAttendanceList()) {
			try {
				try {
					Date d = new SimpleDateFormat("dd-MM-yyyy")
							.parse(attendanceFormModel.getDate());
					if (attendance.getId() != null) {
						Student student = attendance.getId().getStudent();
						// student.setHtno(htno)
						AttendanceId id = new AttendanceId(d,
								attendanceFormModel.getHour(), student);
						attendance.setId(id);
						attendance.setFaculty(attendanceFormModel.getFaculty());
						attendance.setSubject(attendanceFormModel.getSubject());
						// attendance.setAttendance(attendanceFormModel.get)
						alist.add(attendance);
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				model.addAttribute("successMessage",
						Constants.SAVED_SUCCESSFULLY);
			} catch (SaveException exception) {
				model.addAttribute("errorMessage", exception.getErrorMessage());
			}

		}
		collegeService.saveAttendance(alist);
		model.addAttribute("studentList", collegeService.findAllstudents());
		return "attendanceform";
	}
	@RequestMapping(value = "/attendancesearchform")
	public String attendanceSearchForm(
			@ModelAttribute("attendanceFormModel") AttendanceFormModel attendanceFormModel,
			Model model) {
		System.out.println("HomeController: Passing through attendancesearchform...");
		// List<Attendance> attendenceList = new ArrayList<Attendance>();
		//model.addAttribute("studentList", collegeService.findAllstudents());
		// model.addAttribute("attendenceList", attendenceList);
		// model.addAttribute("attendance", new Attendance());
		return "attendancesearchform";
	}
	
	@RequestMapping(value = "/searchattendance")
	public String searchAttendance(@RequestParam("date") String date, @RequestParam("hour") String hour, Model model) {
		System.out.println("HomeController: Passing through searchattendance...");
		List<Attendance> attendanceList = null;
		try {
			attendanceList = collegeService.findAttendance(date, hour);
			//attendanceList = collegeService.findAllAttendance();
			model.addAttribute("successMessage", Constants.SAVED_SUCCESSFULLY);
		} catch (SaveException exception) {
			model.addAttribute("errorMessage", exception.getErrorMessage());
		}
		
		
		model.addAttribute("attendanceList", attendanceList);
		model.addAttribute("date", date);
		model.addAttribute("hour", hour);
		return "attendancereport";
	}
	@RequestMapping(value = "/loginform")
	public String loginForm() {
		System.out.println("HomeController: Passing through loginform...");
		return "login";
	}
	@RequestMapping(value = "/attendance")
	public String attendance() {
		System.out.println("HomeController: Passing through loginform...");
		return "attendance";
	}
	
}